package com.zx.mes.senior.proxy;

import org.junit.Test;
import sun.misc.ProxyGenerator;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * jdk 的动态代理
 * test()方法里一般用于一次性操作
 *
 * @author huayunlong
 * @date 2018-7-30
 */
public class JdkProxyTest {

    @Test
    public void test() {

///        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
        Object proxyInstance = Proxy.newProxyInstance(Person.class.getClassLoader(), new Class[]{IPerson.class}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("打印前做一些事情");
                System.out.println(method);
                System.out.println(args + " : " + args[0]);
                method.invoke(new Person(), args);
                System.out.println("打印后做一些事情");
                return null;
            }
        });


        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy", new Class[]{IPerson.class});
        try (
                FileOutputStream fos = new FileOutputStream(new File("F:/proxyClass/$Proxy.class"))
        ) {
            fos.write(bytes);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }


        ((IPerson) proxyInstance).say("张三");
    }

    @Test
    public void test2() {
        Object instance = Proxy.newProxyInstance(JdkProxyTest.class.getClassLoader(), new Class[]{IPerson.class}, new JdkProxy(new Person()));
        ((IPerson) instance).say("神的再一次光临!");
    }
}
